package com.spsoft.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spsoft.core.annotation.Log;
import com.spsoft.core.constants.CommonConstants;
import com.spsoft.core.entity.VmsLog;
import com.spsoft.core.mapper.VmsLogMapper;
import com.spsoft.core.service.VmsLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spsoft.core.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 * vms数电发票日志表 服务实现类
 * </p>
 *
 * @author dlchen
 * @since 2023-11-07
 */
@Service
@Slf4j
public class VmsLogServiceImpl extends ServiceImpl<VmsLogMapper, VmsLog> implements VmsLogService {

    @Override
    @Async
    public void save(String username, String browser, String ip, ProceedingJoinPoint joinPoint, VmsLog vmsLog) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log aopLog = method.getAnnotation(Log.class);
        // 方法路径
        String methodName =
                joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
        // 描述
        if (vmsLog != null) {
            vmsLog.setDescription(aopLog.value());
            vmsLog.setLogMenuName(aopLog.menuName().getValue());
            vmsLog.setLogActionType(aopLog.type().getValue());
        }
        vmsLog.setRequestIp(ip);

        vmsLog.setMethod(methodName);
        CopyOnWriteArrayList<Object> args = new CopyOnWriteArrayList<>(Arrays.asList(joinPoint.getArgs()));
        args.removeIf(arg -> arg instanceof HttpServletRequest || arg instanceof HttpServletResponse || arg instanceof MultipartFile);
        vmsLog.setUsername(username);
        vmsLog.setCreateBy(username);
        try {
            vmsLog.setParams(JSONObject.toJSONString(args));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        vmsLog.setDelFlag(CommonConstants.DEL_FLAG_0);
        vmsLog.setBrowser(browser);
        Date date = new Date();
        vmsLog.setCreateDay(DateUtils.formatDate(date, "yyyyMMdd"));
        vmsLog.setCreateTime(date);
        log.debug(vmsLog.toString());
        //查询类的接口，不保存数据库
//        if (!LogActionType.SELECT.equals(aopLog.type())) {
        this.save(vmsLog);
//        }
    }
}
